from fastapi import FastAPI, File, UploadFile, HTTPException,Body
from fastapi.middleware.cors import CORSMiddleware
from pathlib import Path
import os
import requests
app = FastAPI()

# CORS 配置：允许从特定域名（如你的前端地址）进行请求
origins = [
    "http://8.130.14.199",
    "http://localhost:5173"# 允许来自该 IP 的请求
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,  # 允许访问的域名
    allow_credentials=True,
    allow_methods=["*"],  # 允许所有请求方法
    allow_headers=["*"],  # 允许所有请求头
)

# 上传目录路径，确保该目录存在
UPLOAD_DIR = "/app/uploads"
os.makedirs(UPLOAD_DIR, exist_ok=True)  # 确保上传目录存在

# 允许上传的文件类型
ALLOWED_IMAGE_TYPES = ["image/jpeg", "image/png", "image/gif", "image/webp"]

@app.post("/upload")
async def upload_file(file: UploadFile = File(...)):
    print(f"Received file: {file.filename}")
    # 检查文件类型
    if file.content_type not in ALLOWED_IMAGE_TYPES:
        raise HTTPException(status_code=400, detail="Invalid file type. Only image files are allowed.")
    # 保存文件
    file_path = Path(UPLOAD_DIR) / file.filename
    try:
        with open(file_path, "wb") as f:
            f.write(await file.read())
        return {
            "status": "success", 
            "filename": file.filename, 
            "message": "File uploaded successfully",
            "file_path": str(file_path),
            "file_name": file.filename
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Failed to save file: {e}")
@app.post("/send")
async def receive_message(message: str = Body(..., embed=True)):
    print(f"Received message in upload_service: {message}")
    
    # 发送消息到容器 B 的 API 端点
    try:
        response = requests.post(
            "http://8.130.14.199:8888/receive_message",  # 使用容器 B 的服务名和端口
            json={"message": message}
        )
        response.raise_for_status()
        return {"status": "success", "message": "Message forwarded to chatqna"}
    except Exception as e:
        return {"status": "error", "message": str(e)}
